#!/usr/bin/env python
# -*- coding: utf-8 -*-
# datetime: 2024/6/10 上午10:34
# Author: name
# File: index.py
# ide: PyCharm
# description:
import json
import time

import jmespath
import uvicorn
from fastapi import FastAPI, Request
from pywebio import config
from pywebio.output import *
from pywebio.platform.fastapi import asgi_app
from pywebio.platform.tornado_http import start_server
from pywebio.output import put_html
import pyecharts.options as opts
from pyecharts.charts import Pie

css = """
.container {
    margin-top: 0;
    max-width: 100%;
}
"""

config(title="测试报告", theme="minty", css_style=css)


def show_test_steps(suit):
    clear("step_list")
    put_text("测试步骤详情", scope="step_list").style(
        "font-size: 20px;font-weight: bold;font-color: black;font-family: 'Microsoft YaHei';")
    print(111, suit)
    data_list = []
    for key, value in suit.items():
        if key != 'step_name' and key != 'step_desc':
            step = []
            if isinstance(value, list):
                for i in value:
                    step.append(put_text(f'{i}'))
            if isinstance(value, dict):
                step.append(put_text(f'{json.dumps(value, ensure_ascii=False, indent=4)}'))
            data_list.append(put_collapse(f'{key}', step, open=True, scope="step_list"))
    return data_list.reverse()


def show_suite_name_list(data):
    put_text(f"测试套件列表({len(data)})", scope="suite_list").style(
        "font-size: 20px;font-weight: bold;font-color: black;font-family: 'Microsoft YaHei';")
    for i in range(len(data)):
        assert_failure_total = jmespath.search("length(@.test_steps[].checker.check_result|[?@==`断言失败`])",
                                               data[i])
        if assert_failure_total > 0:
            color = "secondary"
        else:
            color = "primary"
        step = []
        for item in data[i]["test_steps"]:
            print(1111, item)
            code = f"""
step.append(put_button(item["step_name"]+"："+item["step_name"],onclick=lambda: show_test_steps({item}), color=color))
"""
            exec(code)
        put_collapse(f'{data[i]["suite_name"]}：{data[i]["suite_desc"]}({len(data[i]["test_steps"])})', step, open=False,
                     scope="suite_list")


def show_environment():
    put_text("测试环境", scope="run_environment").style(
        "font-size: 20px;font-weight: bold;font-color: black;font-family: 'Microsoft YaHei';")
    return put_column(
        [
            put_text("操作系统:Windows"),
            put_text("Python版本:3.8.5"),
            put_text("pywebio版本:1.5.1"),
            put_text("pyecharts版本:1.1.0"),
            put_text("jmespath版本:0.10.0"),
        ]
        , scope="run_environment")


def show_api_rate(x_data: list[str], y_data: list[int or float]):
    """
    Gallery 使用 pyecharts 1.1.0
    参考地址: https://echarts.baidu.com/examples/editor.html?c=pie-doughnut

    目前无法实现的功能:

    1、饼状图中间的图例名称暂时无法显示
    """
    #
    # x_data = ["直接访问", "邮件营销", "联盟广告", "视频广告", "搜索引擎"]
    # y_data = [335, 310, 234, 135, 1548]

    c = (
        Pie()
        .add(
            series_name="通过率",
            data_pair=[list(z) for z in zip(x_data, y_data)],
            radius=["50%", "70%"],
            label_opts=opts.LabelOpts(is_show=False, position="center"),
        )
        .set_colors(["green", "red"])
        .set_global_opts(legend_opts=opts.LegendOpts(pos_left="legft", orient="vertical"))
        .set_series_opts(
            tooltip_opts=opts.TooltipOpts(
                trigger="item", formatter="{b}:{c} ({d}%)"
            ),
            # label_opts=opts.LabelOpts(formatter="{b}: {c}")
        )

    )

    c.width = "100%"
    c.height = "100px"
    return put_html(c.render_notebook())


def show_test_result(api_total, x_data, y_data):
    return put_grid([
        [put_row([
            put_html("<h3>接口总数</h3>"),
            None,
            put_html("<h3>通过率</h3>")
        ])],
        [put_row([
            None,
            put_column([put_text(api_total).style("font-size: 50px;"), put_text("test cases")]),
            show_api_rate(x_data, y_data)
        ], size="25% 25% 50%")]
    ], scope="test_result")


def show_report(case_data: list):
    api_total = jmespath.search("length(@[].test_steps[].request.path)", case_data)
    assert_failure_total = jmespath.search("length(@[].test_steps[].checker.check_result|[?@==`断言失败`])", case_data)
    assert_success_total = jmespath.search("length(@[].test_steps[].checker.check_result|[?@==`断言成功`])", case_data)
    x_data = ["测试通过", "测试失败"]
    y_data = [assert_success_total, assert_failure_total]
    suit_name_list = jmespath.search("@[]", case_data)
    print(suit_name_list)
    # 页面布局
    put_text("Test Report").style(
        "font-size: 30px;font-weight: bold;font-color: black;font-family: 'Microsoft YaHei';")
    put_text(f"{time.strftime('%Y/%m/%d')}").style("font-size: 20px;")
    put_row(
        [
            put_column([
                put_scrollable(put_scope('test_result'), height=300, keep_bottom=True)
            ]),
            put_column([
                put_scrollable(put_scope('run_environment'), height=300, keep_bottom=True)
            ])
        ], size="50% 50%"
    )
    put_row([
        put_column([
            put_scrollable(put_scope('suite_list'), height=600, keep_bottom=True)
        ]),
        put_column([
            put_scrollable(put_scope('step_list'), height=600, keep_bottom=True)
        ]),
    ])
    # 页面数据渲染
    show_test_result(api_total, x_data, y_data)
    # 测试环境信息选软
    show_environment()
    # 测试套件列表
    show_suite_name_list(suit_name_list)


# app = FastAPI()
# @app.post("/")
# async def pywebio_entry(request: Request):
#     print(request.json)
#     case_list = await request.json()
#     print(case_list)
#
#     return show_report(case_list)


if __name__ == '__main__':
    case_list = [
        {
            "suite_name": "场景名称_不改的人是pig",
            "suite_desc": "场景描述信息_不改的人是pig",
            "test_steps": None,
            "variables": [
                "局部变量username的值huhaohao保存成功",
                "局部变量password的值123456保存成功",
                "局部变量code的值109保存成功",
                "局部变量code1的值220107_shre保存成功"
            ],
            "set_up": [
                "函数get_str('2dcsxd')的值s已保存为局部变量my_name"
            ],
            "tear_down": [
                "函数get_str('erwewfds')的值w已保存为局部变量password1"
            ],
            "extract": [
                "接口响应中status的值0已保存为局部变量status",
                "接口响应中msg的值Success已保存为局部变量msg",
                "接口响应中data.totalCount的值1613已保存为局部变量totalCount"
            ],
            "request": {
                "path": "/basic/taskInstance/mytaskPagerV2",
                "method": "get",
                "headers": {
                    "Accept": "*/*",
                    "Accept-Language": "zh-CN,zh;q=0.9",
                    "Cache-Control": "no-cache",
                    "Connection": "keep-alive",
                    "Pragma": "no-cache",
                    "Referer": "${host}$/main-project-front/",
                    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
                    "sso-sessionid": "1563101441144979457_1_1_1",
                    "x-account-id": "1563101441144979457",
                    "x-appId-id": "1",
                    "x-employee-id": "1563101440801046530",
                    "x-org-code": "zhzz",
                    "x-org-id": "988377180855869440",
                    "x-tenant-id": "1",
                    "x-user-auth-context": "LGMjb7JsRxNOZjLrYKAjMl3Is5Bu6zAFXQUd4IfOIkAIlYkwrAoqjrxVCethelmFEA3ftpaAwODOjqS/vyRy/D+AKHyPH3GDfQCOU269Pt73nupfJSG1hKNEScRPI9UrppOkQe2uSPKfhIZQwgBUseHvBcFb5wUsMC272eqOGlO/1I7PVF8fq52FCkHXE/ynusvmwX45bQIuA3J4ekcwGxb96uFDQPTDCUq3vyQ+BM4MHzB1ahStUDOEtX3pXewGY2xFrzdmzMeNTMmgQKpkq5f7a/NmbuBHz17wCCc8Xep7Ni+w2S47j3uFR557gZqvhaLkXOZQDwAYhphAMeqhOaBAaZcG6+bmkaWBJiSfzaP9uFJgcTFFzDw5anCvXOo2LMRdw/uQ+BEMxVnZ4i9rGwh2XxdvyCu6kN9ohcReqWH3C+TewRC5n/zjCcKFI0JFDO82FvcV/treiRY8Ni2ue3EtH2WV/war5ex1KYgwXAuFnF4GwDaF1jYcLElD6SNFKqv2gdK2wFu6qCQswdOqo5N7tx2hI+7Qir1b1fVGGzf9+JXuExfGanmkxeAn+2lY5H6GivNBmzzMMDHE1kr5E0KZ26TPRtYFIXeLLzSoRUIC/1gLNsAx/oxVvqDgNN7zhE8kNYXhOmzl4SxD9ayC2+f+xMKusQH2w/QHA07Cj8FTHv6qb4r8K+BBw5vr2jzZ0qdGn/4NyM/l8Dhz5zV68E3Qd7sFLB21acdOPGijZcQwCAN92lvAdAmtayMaVpHNN5Yb8UKIDHOVIDyhr47zNBuqqztg1O5bSb6S41odg+sdftNKVrfqsP1BrSxtkqkDDxu19Y+QXrXkPG62rmff5ZDhVc3WCgU1fme/MjTBFyhcYIA4S9PKVZMhywsKUg2Q6GIJpu0b5evVpqN1Dg71mctvOp6DkNMiF/OZPgsCNccGZ1VlbcovcMJXlqSFPMo4MkhlLIhMRXVSwdKU4mqsQSmZdv1n5wH1TNfvwCwJexqTiOCCW2Jzx6uOeN/T69j1xGYe6kCL0WSL5m1s8OADogZnVWVtyi9wwleWpIU8yjj+nmsjDMqBp7KM1xVgoiVK/SmSzTLnoQ2KkxBxLUvf3k9nSgF7ciAQQiFrH94YJJdCTFxffvfRNvCLh4S+nAru"
                },
                "data": None,
                "params": {
                    "currentPage": "1",
                    "pageSize": "5",
                    "qp-status-in": "0,1,2"
                },
                "files": {}
            },
            "response": {},
            "checker": {
                "check_result": "断言失败",
                "code": 200,
                "json": [
                    "status==`0`断言失败,实际值为0,类型为<class 'str'>",
                    "data.totalCount==`1613`断言失败,实际值为1613,类型为<class 'str'>",
                    "data.pageSize==`5`断言失败,实际值为5,类型为<class 'str'>"
                ],
                "re": [],
                "contains": [
                    "字符串totalCount在响应中",
                    "字符串totalPage在响应中"
                ]
            }
        }
    ]

    start_server(lambda: show_report(case_list), port=8081, cdn=False, debug=True)
    #
    # uvicorn.run(app, port=8081)
